import React, { useState, useEffect } from 'react';
import services from '../../../services/api';
import Compare from '../../../components/Compare';
import { MODULE_TYPE, AUDIT, IS_EXEC_CONDITION, OPER_TYPE } from '../../../utils/constant';
import { Button, Row, Col, message } from 'antd';
import NoData from './NoData';
import PolicyAdd from '../Strategy/add';
import StrategyComponentAdd from '../Strategy/Component/add';
import EventAdd from '../Event/add';
import EventScript from '../Event/script';
import FieldAdd from '../../Variable/Field/add';
import IndicatorAdd from '../../Variable/Indicator/add';
import RiskTypeAdd from '../../Variable/RiskType/add';
import NameListDetail from '../../Variable/NameList/Detail/index';
import MapCompare from '../../Variable/Map/compare';
import ModelCompare from '../../Variable/Model/Model/compare';
import FnAdd from '../../Variable/Fn/add';
import CustomParamsAdd from '../../Variable/Map/CustomParams/add';
import IndexDataSource from '../../Variable/Indicator/DataSource/add';
import PublishCompare from './publishCompare'
import Remark from './remark'
import Modal from '../../../components/Modal';
import { randomKey } from '../../../utils/utils';

export default function AuditCompare(props) {
  const [beforeContent, setBeforeContent] = useState({});
  const [afterContent, setAfterContent] = useState({});
  const [onlineList, setOnlineList] = useState([]);
  const [moduleType, setModuleType] = useState(0);
  const [operType, setOperType] = useState(0);
  const [operType2, setOperType2] = useState(1);

  useEffect(() => {
    getDiffContent(props.record);
  }, []);

  // 通过
  function resolve() {
    const key = randomKey()
    Modal.open({
      title: '',
      width: 360,
      content: <Remark status="1" updateStatus={updateStatus} closeModal={() => Modal.close(key)}></Remark>,
      isOkBtn: false,
      isCancelBtn: false,
      key
    })
  }

  // 拒绝
  function reject() {
    const key = randomKey()
    Modal.open({
      title: '',
      width: 360,
      content: <Remark status="2" updateStatus={updateStatus} closeModal={() => Modal.close(key)}></Remark>,
      isOkBtn: false,
      isCancelBtn: false,
      key
    })
  }
  // 更新审核状态
  function updateStatus(status, audit_remark) {
    services.audit
      .updateStatus({
        audit_ids: [props.record.audit_id],
        status,
        audit_remark
      })
      .then((res) => {
        if (res.code === 0) {
          message.success(res.msg);
          props.dispatch({ type: 'menu/pendingCount', params: {} });
          props.closeModal();
        } else {
          message.warning(res.msg);
        }
      });
  }

  function getDiffContent({ audit_id }) {
    services.audit.getDiffContent({ audit_id }).then((res) => {
      if (res.code === 0) {
        const before_content = res.data.before_content;
        const after_content = res.data.after_content;
        // 如果是策略组件，需要处理下数据
        if (res.data.module_type === MODULE_TYPE._STRATEGY_COMPONENT) {
          if (before_content instanceof Object) {
            before_content.risk_type_f = JSON.stringify(before_content.risk_type);
            before_content.is_exec_condition =
              before_content &&
              before_content.strategy_config &&
              before_content.strategy_config.condition_groups &&
              before_content.strategy_config.condition_groups.length > 0
                ? IS_EXEC_CONDITION._TRUE
                : IS_EXEC_CONDITION._FALSE;
          }
          if (after_content instanceof Object) {
            after_content.risk_type_f = JSON.stringify(after_content.risk_type);
            after_content.is_exec_condition =
              after_content &&
              after_content.strategy_config &&
              after_content.strategy_config.condition_groups &&
              after_content.strategy_config.condition_groups.length > 0
                ? IS_EXEC_CONDITION._TRUE
                : IS_EXEC_CONDITION._FALSE;
          }
        }
        setBeforeContent(before_content);
        setAfterContent(after_content);
        setOnlineList(res.data.online_list || []) // 策略发布需要对比线上数据
        setModuleType(res.data.module_type);
        setOperType(res.data.oper_type);
        setOperType2(res.data.oper_type2); //oper_type2字段的定义主要有：1基础数据 2脚本数据 3明细数据（例如匹配名单，第三方名单需要）
      }
    });
  }

  function getCompareComponent(type, operType2) {
    switch (type) {
      case MODULE_TYPE._RISK_TYPE: // 风险类型
        return RiskTypeAdd;
      case MODULE_TYPE._NAMELIST: // 名单
        return NameListDetail;
      case MODULE_TYPE._THIRD_NAMELIST: // 三方名单
        return MapCompare;
      case MODULE_TYPE._EVENT: // 事件
        // 2脚本数据
        if (operType2 === 2) {
          return EventScript;
        } else {
          return EventAdd;
        }

      case MODULE_TYPE._FIELD: // 字段
        return FieldAdd;
      case MODULE_TYPE._STRATEGY: // 策略
        return PolicyAdd;
      case MODULE_TYPE._MODEL: //模型
        return ModelCompare;
      case MODULE_TYPE._FEATURE: //指标
        return IndicatorAdd;
      case MODULE_TYPE._ACTION: // 函数
        return FnAdd;
      case MODULE_TYPE._INDEX_DATASOURCE: // 指标数据源
        return IndexDataSource;
      case MODULE_TYPE._STRATEGY_COMPONENT: // 策略组件
        return StrategyComponentAdd;
      case MODULE_TYPE._CUSTOM_PARAMS: // 自定义出参
        return CustomParamsAdd;
      case MODULE_TYPE._MAP: // 映射
        return MapCompare;
      default:
        return NoData;
    }
  }
  const Com = getCompareComponent(moduleType, operType2);

  return (
    <div>
      <div
        className={moduleType === MODULE_TYPE._STRATEGY ? 'stretegy-content' : null}
        style={moduleType === MODULE_TYPE._STRATEGY ? { marginBottom: '30px' } : null}
      >
        {(moduleType === MODULE_TYPE._STRATEGY && operType === OPER_TYPE._PUBLISH) ?
          <PublishCompare
            {...props}
            afterContent={afterContent}
            onlineList={onlineList}
            operType={operType && operType}
          >
          </PublishCompare> :
          <Compare
          beforeCom={
            <div>
              <Com
                {...props}
                value={beforeContent || {}}
                compareData={afterContent || {}}
                actionType='detail'
                isOld={true}
                isCompare={true}
                isImport={operType === OPER_TYPE._INPORT ? true : false}
                isImportant={operType === OPER_TYPE._INPORT}
              />
            </div>
          }
          afterCom={
            <div>
              <Com
                {...props}
                value={afterContent || {}}
                compareData={beforeContent || {}}
                actionType='detail'
                isOld={false}
                isCompare={true}
                isImport={operType === OPER_TYPE._INPORT ? true : false}
                isImportant={operType === OPER_TYPE._INPORT}
                actions={(afterContent || {}).actions}
              />
            </div>
          }
          operType={operType && operType}
        />}
      </div>

      <Row type='flex' gutter={10} justify='center'>
        {props.record.status === AUDIT._WAIT ? (
          <>
            <Col>
              <Button autoFocus={true} type='primary' onClick={() => resolve()}>
                通过
              </Button>
            </Col>

            <Col>
              <Button onClick={() => reject()}>拒绝</Button>
            </Col>
            <Col>
              <Button onClick={() => props.closeModal(true)}>取消</Button>
            </Col>
          </>
        ) : (
          <>
            <Col>
              <Button type='primary' autoFocus={true} onClick={() => props.closeModal(true)}>
                确定
              </Button>
            </Col>
            <Col>
              <Button onClick={() => props.closeModal(true)}>取消</Button>
            </Col>
          </>
        )}
      </Row>
    </div>
  );
}
